/**
* @Title: ChannelSupervise.java
* @Package com.cenntro.common.websocket
* @Description: 
* @author Administrator
* @date 2019年7月25日
* @version V1.0
*/
package com.cenntro.common.websocket;

import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.security.auth.Subject;

import org.apache.commons.collections.MapUtils;

import com.google.common.collect.Lists;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
* @ClassName: ChannelSupervise
* @Description: TODO
* @author Administrator
* @date 2019年7月25日
*
*/
public class ChannelSupervise {

    public static ChannelGroup GlobalGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * channelId,channelId
     */
    private static ConcurrentMap<String, ChannelId> ChannelMap = new ConcurrentHashMap<String, ChannelId>();

    /**
     * key 用户session，value channelId
     */
    private static ConcurrentMap<String, String> sessionmap = new ConcurrentHashMap<String, String>();

    public static void addChannel(Channel channel, String userSession) {
        GlobalGroup.add(channel);
        ChannelMap.put(channel.id().asShortText(), channel.id());
        sessionmap.put(userSession, channel.id().asShortText());
    }

    /**
     * 
    * @Title removeChannel
    * @Description TODO
    * @param 
    * @return
     */
    public static void removeChannel(Channel channel) {
        GlobalGroup.remove(channel);
       
        ChannelMap.remove(channel.id().asShortText());
        for (Entry<String, String> en : sessionmap.entrySet()) {
            if (channel.id().asShortText().equals(en.getValue())) {
                sessionmap.remove(en.getKey());
                break;
            }
        }
    }

    public static Channel findChannel(String channelId) {
        return GlobalGroup.find(ChannelMap.get(channelId));
    }

    public static void send2All(TextWebSocketFrame tws) {
        GlobalGroup.writeAndFlush(tws);
    }

    /**
     * 
    * @Title send
    * @Description TODO
    * @param 
    * @return
     */
    public static List<String> send(String[] sessionId, String message) {
        List<String> list = Lists.newArrayList();
        for (String id : sessionId) {
            String channelId = sessionmap.get(id);
            if(channelId != null){
                Channel ch = GlobalGroup.find(ChannelMap.get(channelId));
                if(ch != null && ch.isActive()){
                    ch.writeAndFlush(new TextWebSocketFrame(message));
                    list.add(id);
                }
            }
        }
        return list;
    }
}
